console.log('tax injected');
/*
 * 厦门全是季报
 * */

import { transformDataByOpenWeb } from './../../lib/openWebTransform.js';
import { syncReportInfoHelper } from './help.js';

let baseInfo;

window.onload = function() {
  // 登录填写账号密码
  if (/\/wsbs\/toLogin.do/g.test(window.location.pathname)) {
    window.postMessage(
      {
        event: 'getBaseInfo'
      },
      '*'
    );
  }
};

window.addEventListener(
  'message',
  async function({ data }) {
    // 只监听来自于content script的信息
    if (data.sender !== 'content-script') {
      return false;
    }
    if (data.event === 'setSaasData') {
      data = data.data;
      let sheet = data.saasData.sheet;
      console.log(data);
      if (sheet == 'sds' || sheet == 'zzs') {
        fillInput(data, sheet);
      } else {
        await fillInput(await transformDataByOpenWeb(data));
      }
    }
    if (data.event === 'getNationData') {
      getNationData();
    }

    if (data.event === 'getBaseInfo') {
      baseInfo = data.data;
      autoInputAccount(baseInfo);
    }

    // 同步申报表种类
    if (data.event === 'syncReportInfo') {
      syncReportInfoHelper.startGetReportInfo();
    }
    // 同步申报表
    if (data.event === 'syncReport') {
      syncReportInfoHelper.startGetReport();
    }
  },
  false
);
/**
 * 获取公司信息
 */
function getNationData() {
  let taxInfo = {
    institution: '2013', // 国税对应制度 2007 | 2013
    nsrsbh: '', // 纳税人申报号
    nsrmc: '', // 纳税人名称（纳税公司）
    skssqq: '', // 税款所属期起
    skssqz: '' // 税款所属期止
  };
  window.postMessage(
    {
      event: 'backNationData',
      data: {
        taxInfo: taxInfo
      }
    },
    '*'
  );
}

function autoInputAccount({ companyInfo }) {
  companyInfo = companyInfo || {};
  console.log(companyInfo);
  if (/\/wsbs\/toLogin.do/g.test(window.location.pathname)) {
    // document.querySelector("#home_nsrsbh")
    $('#home_nsrsbh').val(companyInfo.nationalTaxAccount);
    $('#home_password').val(companyInfo.nationalTaxPass);
  }
}

const names = {
  profit: '利润表',
  balance: '资产负债表',
  cash: '现金流量表'
};

async function fillInput({ saasData }) {
  let sheet = saasData.sheet;
  let maoBaobiao = {
    balance: 'zcfzb',
    profit: 'lrb',
    cash: 'xjllb'
  };
  let $iframe = $('iframe').contents();
  let table = $iframe.find(`#${maoBaobiao[sheet]}`);
  let trs = table.find('tr');
  let inputArea = table.find('.inputArea');
  let arr = Object.keys(saasData.data);
  if (sheet === 'cash') {
    let arr2 = arr.filter(item => item.charAt(item.length - 1) === '2');
    let arr3 = arr.filter(item => item.charAt(item.length - 1) === '3');
    arr = [...arr3, ...arr2];
  }
  let message = '填报成功';
  try {
    arr.map(key => {
      let row = key.split('l')[0].replace('h', '');
      let col = parseInt(key.split('l')[1]);
      if (col === 2) col = 3;
      else if (col === 3) col = 4;
      else if (col === 5) col = 7;
      else if (col === 6) col = 8;
      let current = Array.from(trs).find(item => $(item).find('td:nth-child(2)').text() === row);
      let td = $(current).find(`td:nth-child(${col})`);
      if (!td.attr('iseditable')) {
        td.click();
        inputArea.val(saasData.data[key]);
        return true;
      }
    });
    if (sheet === 'balance') {
      let current = Array.from(trs).find(item => $(item).find('td:nth-child(2)').text() === '28');
      let td = $(current).find('td:nth-child(7)');
      td.click();
      inputArea.val(saasData.data.h29l5);
      let td1 = $(current).find('td:nth-child(8)');
      td1.click();
    }
    return true;
  } catch (e) {
    message = '填报失败' + e;
  }

  // let tableType;
  // const typeSign = $iframe.$$('input[name=SwordTreeJSON]')[0];
  // const checkType = typeSign.getAttribute('originvalue') || '资产负债表';
  // if (!checkType.includes(names[sheet])) {
  //   alert('填报报表与一键报税填报报表类型不匹配请核实');
  //   return;
  // }

  // if (sheet !== 'balance') {
  //   $iframe = $iframe.$(`table${typeSign.getAttribute('realvalue')}iframe`)
  //     .contentWindow;
  // }
  // tableType = $iframe.$$('.swordfrom_div')[1].getAttribute('name');

  // let message = '填报成功';
  // try {
  //   let inputData = saasData.data;
  //   if (sheet == 'sds' || sheet == 'zzs') {
  //     inputData = delSdsData(inputData.openParams.inputData.data.profit);
  //   }
  //   for (let key in inputData) {
  //     const input = $iframe.$$(`#${tableType}_${key}`);
  //     input
  //       .set('value', inputData[key])
  //       .set('realvalue', inputData[key])
  //       .fireEvent('change');
  //   }
  // } catch (e) {
  //   message = '填报失败' + e;
  // }

  // todo finally
  window.postMessage(
    {
      event: 'fillInputDone',
      data: {
        message: message
      }
    },
    '*'
  );
}

function delSdsData(tableData) {
  let sdsData = {};
  sdsData.yysr = tableData.BNLJJE_1;
  sdsData.yycb = tableData.BNLJJE_2;
  sdsData.lrze = tableData.BNLJJE_30;
  return sdsData;
}

function getTaxType(typeStr) {
  let taxType;
  if (typeStr.search('增值税') != -1) {
    taxType = 'zzs';
  } else if (typeStr.search('所得税') != -1) {
    taxType = 'sds';
  } else if (typeStr.search('财务报表') != -1) {
    taxType = 'RptBalanceSheet';
  }
  return taxType;
}

function sendFilter(typeStr, timeStart, timeEnd) {
  let sssq_q = timeStart.replace(/\//g, '').substr(0, 6),
    sssq_z = timeEnd.replace(/\//g, '').substr(0, 6);
  let taxType = getTaxType(typeStr);
  if (sssq_q && sssq_z) {
    window.postMessage(
      {
        event: 'setPeriodAndType',
        data: {
          type: taxType,
          startTime: sssq_q.replace(/(\d{4})/g, '$1-'),
          endTime: sssq_z.replace(/(\d{4})/g, '$1-')
        }
      },
      '*'
    );
  } else if (taxType) {
    window.postMessage(
      {
        event: 'setPeriodAndType',
        data: {
          type: taxType
        }
      },
      '*'
    );
  }
}
